<?php 
namespace Common\Model;

class GoodsModel extends BaseModel{
    protected $tableName = 'mall_goods';
    
    /**
     * 添加商品
     * @param Goods $data
     * @return number
     */
    public function insert($data){
        $tagIds = $data['tag_ids'];
        $products = $data['products'];
        unset($data['tag_ids']);
        unset($data['products']);
        $goods = $data;
        $goods['pic_url'] = $data['images'][0];
        $goods['images'] = json_encode($data['images']);
        $goods['sold_time'] = empty($data['sold_time']) ? 0 : strtotime($data['sold_time']);
        $goods['created'] = date('Y-m-d H:i:s');
        $goods['sku_json'] = is_array($data['sku_json']) ? json_encode($_POST['sku_json'], JSON_UNESCAPED_UNICODE) : '[]';
        if($data['cat_id'] == 2){
            $goods['pay_type'] = 4; // 拼手气红包
        }else if($data['cat_id'] == 3){
            $goods['pay_type'] = 5; // 裂变红包
        }
        
        if($goods['pay_type'] == 4 || $goods['pay_type'] == 5){
            $goods['returns'] = 0;
            $goods['original_price'] = '';
        }
        
        // 添加商品
        $goodsId = $this->add($goods);
        if($goodsId < 1)
            return 0;
        $goods['id'] = $goodsId;
        
        // 分组处理
        $this->addTag($goodsId, $tagIds);
        
        // 产品处理
        if(is_array($products) && count($products) > 0){
            foreach($products as $i=>$item){
                $products[$i]['goods_id'] = $goodsId;
                $products[$i]['pic_url'] = '';
                
                // 处理产品图片
                foreach($data['sku_json'] as $psku){
                    foreach($psku['items'] as $vsku){
                        if(!empty($vsku['img'])){
                            foreach($item['sku_json'] as $pcsku){
                                if($pcsku['vid'] == $vsku['id']){
                                    $products[$i]['pic_url'] = $vsku['img'];
                                    goto end;
                                }
                            }
                        }
                    }
                }
                end:
            }
        }else{
            $products = array(
                'goods_id'      => $goodsId,
                'stock'         => $goods['stock'],
                'price'         => $goods['price'],
                'outer_id'      => $goods['outer_id'],
                'original_price'=> $goods['original_price'],
                'pic_url'       => $goods['pic_url'],
                'weight'        => $goods['weight'],
                'agent2_price'  => $goods['agent2_price'],
                'agent3_price'  => $goods['agent3_price'],
                'cost'          => $goods['cost']
            );
        }
        $this->addProduct($products);
        
        $this->updateGoodsSort($goods);
        return 1;
    }
    
    /**
     * 为goods和tag建立关系
     * @param unknown $goodsId
     * @param unknown $tags
     * @return \Think\false
     */
    public function addTag($goodsId, $tags){
        $this->execute("DELETE FROM mall_goods_tag WHERE goods_id=".$goodsId);
        if($tags == ''){
            return;
        }
        
        $tags = explode(',', $tags);
        $sql = "INSERT INTO mall_goods_tag(tag_id, goods_id) VALUES";
        $values = array();
        foreach($tags as $id){
            $values[] = "('{$id}', '{$goodsId}')";
        }
        $sql .= implode(',', $values);
        return $this->execute($sql);
    }
    
    /**
     * 添加产品/多个产品
     * @param unknown $products
     */
    public function addProduct($products){
        $Model = M('mall_product');
        $today = date('Y-m-d H:i:s');
        if(isset($products[0])){
            $list = array();
            foreach($products as $item){
                $item['created'] = $today;
                unset($item["id"]);
                if(is_array($item['sku_json'])){
                    $item['sku_json'] = json_encode($item['sku_json'], JSON_UNESCAPED_UNICODE);
                }
                $list[] = $item;
            }
            return $Model->addAll($list);
        }else{
            $products['created'] = $today;
            if(is_array($products['sku_json'])){
                $products['sku_json'] = json_encode($products['sku_json'], JSON_UNESCAPED_UNICODE);
            }
            return $Model->add($products);
        }
    }
    
    /**
     * 更新产品七日上架时间(排序)
     */
    private function updateGoodsSort($goods){
        $goodsId     = $goods['id'];
        $displayTime = $goods['sold_time'] == 0 ? time() : $goods['sold_time'];
        $sort = is_numeric($goods['sort']) ? $goods['sort'] : 0;
        
        $now = NOW_TIME;
        $this->execute("INSERT INTO mall_goods_sort(goods_id, sort, display_time) VALUES({$goodsId}, {$sort}, {$displayTime}) 
                        ON DUPLICATE KEY UPDATE sort=VALUES(sort), display_time={$displayTime}");
    }
    
    /**
     * 复制商品
     * @author Liucong
     */
    public function copy($id){
        $data = $this->getById($id);
        $data['pv'] = 0;
        $data['uv'] = 0;
        $data['sold_num'] = 0;
        $data['order_num'] = 0;
        $data['sku_json'] = is_array($data['sku_json']) ? json_encode($data['sku_json'], JSON_UNESCAPED_UNICODE) : '';
        if(empty($data['weight'])){
                unset($data['weight']);
        }
        unset($data['id']);
        foreach($data['products'] as $key => $value){
                unset($data['products'][$key]['id']);
                if(empty($value['modified'])){
                        unset($data['products'][$key]['modified']);
                }
                $data['products'][$key]['sold_num'] = 0;
                $data['products'][$key]['order_num'] = 0;
                $data['products'][$key]['pv'] = 0;
                $data['products'][$key]['uv'] = 0;
        }
        $result = $this->insert($data);
        return $result;
    }
    
    /**
     * 根据id获取商品信息
     * @param unknown $id
     * @return NULL|Ambigous <mixed, boolean, NULL, string, unknown, multitype:, object>
     */
    public function getById($id){
        $goods = $this
                 ->alias("goods")
                 ->field("goods.id, goods.sold_time, goods.buy_quota, goods.cat_id, goods.pay_type, 
                     goods.title, goods.agent2_price, goods.agent3_price, goods.agent4_price, goods.price, 
                     goods.original_price, goods.score, goods.stock, goods.hide_stock, goods.outer_id, 
                     goods.pic_url, goods.images, goods.digest, goods.day_quota, goods.every_quota, 
                     goods.agent_quota, goods.is_virtual, goods.freight_tid, goods.freight_type, 
                     goods.member_discount, goods.points, goods.is_display, goods.sold_num, goods.order_num,
                     goods.invoice, goods.warranty, goods.`returns`, goods.created, goods.sku_json, 
                     goods.template_id, goods.is_del, goods.weight, goods.shop_id, goods.tao_id, goods.parameters,
                     shop.name AS shop_name")
                 ->join("shop ON shop.id=goods.shop_id")
                 ->where("goods.id=".$id)
                 ->find();
        
        if(empty($goods)){
            $this->error = '商品不存在';
            return null;
        }
        
        return $this->formatter($goods);
    }
    
    private function formatter($goods){
        // 格式化数据
        $goods['sale_distance'] = 0;
        if($goods['sold_time'] > 0){
            $now = time();
            if($goods['sold_time'] > $now){
                $goods['sale_distance'] = $goods['sold_time'] - $now;
            }
        
            $goods['sold_time'] = date('Y-m-d H:i:s', $goods['sold_time']);
        }
        
        $goods['price'] = sprintf("%.2f", $goods['price']);
        if($goods['original_price'] > 0){
            $goods['original_price'] = sprintf("%.2f", $goods['original_price']);
        }
        $goods['images'] = json_decode($goods['images'], true);
        
        // 分组
        $tags = $this->query("SELECT GROUP_CONCAT(tag_id) FROM mall_goods_tag WHERE goods_id='%d'", $goods['id']);
        $goods['tag_ids'] = current($tags[0]);
    
        // sku组合
        $goods['sku_json'] = $goods['sku_json'] ? json_decode($goods['sku_json'], true) : array();
    
        // 参数
        if(isset($goods['parameters'])){
            $goods['parameters'] = json_decode($goods['parameters'], true);
        }
    
        // 产品
        $products = $this->query("SELECT * FROM mall_product WHERE goods_id='%d'", $goods['id']);
        foreach($products as $i=>$item){
            $products[$i]['sku_json'] = ($item['sku_json'] && $item['sku_json'] != '[]') ? json_decode($item['sku_json'], true) : array();
        }
        $goods['products'] = $products;
        
        /************************************/
        // 限购处理
        $limit = array();
        $goods['quota'] = $goods['stock'];
        $todayStart     = date('Y-m-d').' 00:00:00';
        $todayEnd       = date('Y-m-d').' 23:59:59';
        
        // 日限购处理(同时处理库存)
        if($goods['day_quota'] > 0){
            $limit[] = '每日限售'.$goods['day_quota'].'件';
            
            $OrderModel = D('Order');
            $soldNum = $OrderModel->getSoldNumByTime($goods['id'], $todayStart, $todayEnd);
            if($soldNum >= $goods['day_quota']){
                $goods['stock'] = 0;
            }else{
                $stock = $goods['day_quota'] - $soldNum;
                $goods['stock'] = $goods['stock'] < $stock ? $goods['stock'] : $stock;
            }
        
            $goods['quota'] = $goods['stock'];
        }
        
        // 每人每日限购处理
        if($goods['every_quota'] > 0){
            $limit[] = '每日限购'.$goods['every_quota'].'件';
            if($goods['quota'] > 0){
                $quota = $goods['stock'] < $goods['every_quota'] ? $goods['stock'] : $goods['every_quota'];
                if($quota < $goods['quota']){
                    $goods['quota'] = $quota;
                }  
            }
        }
        
        // 每人最多能购买
        if($goods['buy_quota'] > 0){
            $limit[] = '每人限购'.$goods['buy_quota'].'件';
            if($goods['quota'] > 0){
                $quota = $goods['stock'] < $goods['buy_quota'] ? $goods['stock'] : $goods['buy_quota'];
                if($quota < $goods['quota']){
                    $goods['quota'] = $quota;
                }
            }
        }
        
        if($goods['quota'] > 0 && ($goods['pay_type'] == 4 || $goods['pay_type'] == 5)){
            $goods['quota'] = 1;
        }
        $goods['quota_str'] = count($limit) > 0 ? implode(',', $limit) : '';
        /*************************************/
        
        // 发货地
        if(isset($goods['send_place'])){
            if($goods['send_place'] > 0){
                $city = StaticModel::getCityList($goods['send_place']);
                $province = StaticModel::getCityList($city['pcode']);
                $goods['send_place'] = $province['sname'].' '.$city['sname'];
            }else{
                $goods['send_place'] = '';
            }
        }
        
        // 偏远地区
        if(isset($goods['remote_area']) && !empty($goods['remote_area'])){
            $remoteAreas = explode(',', $goods['remote_area']);
            $remoteArea = '';
            foreach ($remoteAreas as $code){
                $city = StaticModel::getCityList($code);
                $remoteArea .= $remoteArea == '' ? $city['sname'] : '、'.$city['sname'];
            }
            $goods['remote_area'] = $remoteArea;
        }
        
        // 快递费
        if(isset($goods['freight_tid'])){
            if($goods['freight_tid'] == 'T1'){ // 包邮
                $goods['freight_fee'] = '免邮';
            }else if(is_numeric($goods['freight_tid'])){
                $EM = new \Common\Model\ExpressModel();
                $freightFee = $EM->getMinFree($goods['freight_tid'], $goods['weight']);
                $goods['freight_fee'] = $freightFee == 0 ? '免邮' : $freightFee;
            }else{
                $goods['freight_fee'] = '未知';
            }
        }
        return $goods;
    }
    
    /**
     * 更新商品信息
     * @param unknown $goods
     */
    public function update($data){
        $goodsId = $data['id'];
        if(!is_numeric($goodsId)){
            $this->error = '商品id不能为空';
            return -1;
        }
        
        $old = $this->getById($goodsId);
        
        $tagIds = $data['tag_ids'];
        $products = $data['products'];
        unset($data['tag_ids']);
        unset($data['products']);
        $goods = $data;
        $goods['pic_url'] = $data['images'][0];
        $goods['images'] = json_encode($data['images']);
        $goods['sold_time'] = empty($data['sold_time']) ? 0 : strtotime($data['sold_time']);
        $goods['sku_json'] = is_array($data['sku_json']) ? json_encode($_POST['sku_json'], JSON_UNESCAPED_UNICODE) : '[]';
        if($data['cat_id'] == 2){
            $goods['pay_type'] = 4; // 拼手气红包
        }else if($data['cat_id'] == 3){
            $goods['pay_type'] = 5; // 裂变红包
        }
        
        if($goods['pay_type'] == 4 || $goods['pay_type'] == 5){
            $goods['returns'] = 0;
            $goods['original_price'] = '';
        }
        
        // 保存GOODS
        $this->where("id=".$goodsId)->save($goods);
        
        // 保存TAG
        if($tagIds != $data['tag_ids']){
            $this->addTag($goodsId, $tagIds);
        }
        
        // 保存PRODUCT
        if(is_array($products) && count($products) > 0){
            $existsIds = array();
            foreach($products as $product){
                // 处理产品图片
                $product['pic_url'] = '';
                foreach($data['sku_json'] as $psku){
                    foreach($psku['items'] as $vsku){
                        if(!empty($vsku['img'])){
                            foreach($product['sku_json'] as $pcsku){
                                if($pcsku['vid'] == $vsku['id']){
                                    $product['pic_url'] = $vsku['img'];
                                    goto end;
                                }
                            }
                        }
                    }
                }
                end:
                
                if(is_numeric($product['id'])){
                    $this->updateProduct($product);
                    $existsIds[] = $product['id'];
                }else{
                    $product['goods_id'] = $goodsId;
                    $this->addProduct($product);
                }
            }

            // 取出已被摒弃的产品ID
            $deletedIds = array();
            foreach($old['products'] as $product){
                if(!in_array($product['id'], $existsIds)){
                    $deletedIds[] = $product['id'];
                }
            }
            
            // 删除摒弃的产品
            if(count($deletedIds) > 0){
                $sql = "DELETE FROM mall_product WHERE id IN (".implode(',', $deletedIds).")";
                $this->execute($sql);
            }
        }else{
            $product = array(
                'goods_id'      => $goodsId,
                'stock'         => $goods['stock'],
                'price'         => $goods['price'],
                'pic_url'       => '',
                'outer_id'      => $goods['outer_id'],
                'pic_url'       => $goods['pic_url'],
                'weight'        => $goods['weight'],
                'agent2_price'  => $goods['agent2_price'],
                'agent3_price'  => $goods['agent3_price'],
                'cost'          => $goods['cost']
            );
            
            if(empty($old['sku_json'])){
                $product['id'] = $old['products'][0]['id'];
                $this->updateProduct($product);
            }else{
                $this->execute("DELETE FROM mall_product WHERE goods_id=".$goodsId);
                $this->addProduct($product);
            }
        }
        
        $this->updateGoodsSort($goods);
        return 1;
    }
    
    /**
     * 更新单个产品(不更新goods表库存)
     * @param unknown $product
     * @return number|boolean
     */
    public function updateProduct($product){
        if(!is_numeric($product['id'])){
            $this->error = '产品ID不能为空';
            return -1;
        }
        
        $Model = M('mall_product');
        if(is_array($product['sku_json'])){
            $product['sku_json'] = json_encode($product['sku_json'], JSON_UNESCAPED_UNICODE);
        }
        $Model->where("id=%d", $product['id'])->save($product);
    }
    
    /**
     * 批量更新产品(自动更新goods表库存)
     * @param unknown $products
     */
    public function updateProducts($goodsId, $products){
        $Model = M('mall_product');
        $minPrice = -1;
        foreach($products as $id=>$product){
            $Model->where("id=".$id)->save($product);
            
            if($minPrice < 0 || $product['price'] < $minPrice){
                $minPrice = $product['price'];
            }
        }
        
        $this->execute("UPDATE mall_goods SET price='{$minPrice}', stock=(SELECT SUM(stock) FROM mall_product WHERE goods_id={$goodsId}) WHERE id={$goodsId}");
    }
    
    /**
     * 根据id删除商品
     * @param unknown $goodsIds
     * @param string $shopId
     * @return number
     */
    public function deleteById($goodsIds, $shopId = null){
        if(empty($goodsIds)){ 
            $this->error = '商品ID不能为空';
            return  -1;
        }
        
        $sql = "UPDATE ".$this->tableName." SET is_del=1 WHERE `id` IN ({$goodsIds})";
        if(is_numeric($shopId)){
            $sql .= "  AND shop_id=".$shopId;
        }
        
        $result = $this->execute($sql);
        if($result > 0){
            $this->execute("DELETE FROM mall_goods_sort WHERE goods_id IN ({$goodsIds})");
        }
        return $result;
    }
    
    /**
     * 批量下架
     * @param unknown $goodsIds
     * @param string $shopId
     * @return number|\Think\false
     */
    public function takeDown($goodsIds, $shopId = null){
        if(empty($goodsIds)){ 
            $this->error = '商品ID不能为空';
            return  -1;
        }
        
        $sql = "UPDATE ".$this->tableName." SET is_display=0 WHERE `id` IN ({$goodsIds})";
        if(is_numeric($shopId)){
            $sql .= " AND shop_id=".$shopId;
        }
        return $this->execute($sql);
    }
    
    /**
     * 批量上架
     * @param unknown $goodsIds
     * @param string $shopId
     * @return number|\Think\false
     */
    public function takeUp($goodsIds, $shopId = null){
        if(empty($goodsIds)){ 
            $this->error = '商品ID不能为空';
            return  -1;
        }
        
        $sql = "UPDATE ".$this->tableName." SET is_display=1 WHERE `id` IN ({$goodsIds})";
        if(is_numeric($shopId)){
            $sql .= " AND shop_id=".$shopId;
        }
        return $this->execute($sql);
    }
    
    /**
     * 
     * @param unknown $goodsIds
     * @param unknown $join
     * @param string $shopId
     * @return number|\Think\false
     */
    public function discount($goodsIds, $join, $shopId = null){
        if(empty($goodsIds)){
            $this->error = '商品ID不能为空';
            return  -1;
        }
        
        $sql = "UPDATE ".$this->tableName." SET member_discount=".($join ? 1 : 0)." WHERE `id` IN ({$goodsIds})";
        if(is_numeric($shopId)){
            $sql .= " AND shop_id=".$shopId;
        }
        return $this->execute($sql);
    }
    
    /**
     * 获取首页展示的商品
     * @param unknown $shopId
     */
    public function getHomeGoods($myLevel){
        $offset = is_numeric($_GET['offset']) ? $_GET['offset'] : 0;
        $size = is_numeric($_GET['size']) ? $_GET['size'] : 38;
        $title = $_GET['title'];
        $sort = $_GET['sort'];
        
        $where = array('goods.is_display=1', 'goods.is_del=0');
        $order = '';
        switch ($sort){
            case 'newest':
                $order = 'goods_sort.display_time DESC';
                break;
            case 'sales':
                $order = 'goods_sort.threeday DESC';
                break;
            case 'hot':
                $order = 'goods_sort.uv DESC';
                break;
            default:
                $order = 'goods_sort.sort DESC, goods_sort.display_time DESC, goods_sort.uv DESC';
                break;
        }
        
        if($title != ''){
            $where[] = "goods.title like '%".addslashes($title)."%'";
        }
        
        if(is_numeric($_GET['shop_id'])){
            $where[] = "goods.shop_id ='".$_GET['shop_id']."'";
        }
        
        if(is_numeric($_GET['cat'])){
            $where[] = "goods.cat_id ='".$_GET['cat']."'";
        }
        
        $field = "goods.id, goods.title, goods.price, goods.original_price, goods.pic_url, 
                  goods.images, goods.agent2_price, goods.agent3_price, goods.visitors_quota, goods.weight, goods.freight_type";
        if($_GET['tag_id'] == 'jinribaokuan'){   // 今日爆款
            $where = count($where) > 0 ? "WHERE ".implode(' AND ', $where) : '';
            $sql = "SELECT {$field}
                    FROM (
                    	SELECT goods_sort.*
                    	FROM mall_goods AS goods
                    	INNER JOIN mall_goods_sort AS goods_sort ON goods_sort.goods_id=goods.id
                    	WHERE goods.is_display=1
                    	ORDER BY goods_sort.yesterday DESC
                    	LIMIT 114
                    ) AS goods_sort
                    LEFT JOIN mall_goods AS goods ON goods.id=goods_sort.goods_id
                    {$where}
                    ORDER BY {$order} 
                    LIMIT {$offset}, {$size}";
        }else if(is_numeric($_GET['tag_id']) || preg_match('/^(\d+,){2,}$/', $_GET['tag_id'].',')){
            $where   = count($where) > 0 ? "WHERE ".implode(' AND ', $where) : "";
            $sql = "SELECT {$field}
                    FROM mall_goods AS goods
                    INNER JOIN mall_goods_sort AS goods_sort ON goods_sort.goods_id=goods.id
                    INNER JOIN mall_goods_tag AS tag ON tag.goods_id=goods.id AND tag.tag_id in ({$_GET['tag_id']})
                    {$where}
                    ORDER BY {$order} 
                    LIMIT {$offset}, {$size}";
        }else{
            if($_GET['tag_id'] == 'baoyou'){
                $where[] = 'goods.freight_type=0';
            }
            
            $where   = count($where) > 0 ? "WHERE ".implode(' AND ', $where) : "";
            $sql = "SELECT {$field}
                    FROM mall_goods AS goods
                    INNER JOIN mall_goods_sort AS goods_sort ON goods_sort.goods_id=goods.id
                    {$where}
                    ORDER BY {$order}
                    LIMIT {$offset}, {$size}";
        }
        
        $list = $this->query($sql);
        if(count($list) > 0){
            // 页面数据显示处理
            foreach($list as $k=>$goods){
                $list[$k] = $this->goodsHandler($goods, $myLevel);
            }
        
            // 保存搜索历史记录
            if($title != ''){
                $search = cookie('search_goods');
                $searchList = !empty($search) ? explode(';', $search) : array();
                $key = array_search($title, $searchList);
                if($key !== false){
                    array_splice($searchList, $key, 1);
                }
                array_unshift($searchList, $title);
                if(count($searchList) > 20){
                    array_splice($searchList, 20);
                }
                $search = implode(';', $searchList);
                cookie('search_goods', $search, 2592000);
            }
        }
        
        return $list;
    }
    
    /**
     * 猜你喜欢
     */
    public function getLikeGoods($user){
        $uid = $user['id'];
        $myLevel = $user['agent_level'];
        
        // 查找浏览历史记录
        $sql = "SELECT DISTINCT tag.tag_id
                FROM mall_goods_uv AS uv 
                INNER JOIN mall_goods_tag AS tag ON tag.goods_id = uv.goods_id 
                WHERE user_id = {$uid}
                ORDER BY date DESC
                LIMIT 5";
        $earchResult = $this->query($sql);
        
        $sql = '';
        if(count($earchResult) > 0){
            $tagId = '';
            foreach ($earchResult as $item){
                $tagId .= $item['tag_id'].',';
            }
            $tagId = rtrim($tagId, ',');
            $sql = "SELECT id, title, price, original_price, pic_url, images, agent2_price, agent3_price, visitors_quota, weight, freight_type
                    FROM
                    (
                    	SELECT goods_id
                    	FROM mall_goods_tag
                    	WHERE tag_id IN ({$tagId})
                    	ORDER BY RAND()
                    	LIMIT 1000
                    ) AS tag
                    INNER JOIN mall_goods AS goods ON goods.id = tag.goods_id
                    WHERE goods.is_display = 1 AND goods.is_del = 0
                    LIMIT 57";
        }else{
            $sql = "SELECT goods.id, title, price, original_price, pic_url, images, agent2_price, agent3_price, visitors_quota, weight, freight_type
                    FROM mall_goods AS goods
                    JOIN ( SELECT ROUND( RAND() * (SELECT MAX(id) - MIN(id) FROM mall_goods) + (SELECT MIN(id) FROM mall_goods) ) AS id) AS t2
                    WHERE goods.id>=t2.id
                        AND goods.is_display=1 AND goods.is_del=0
                    LIMIT 57";
        }
        $list = $this->query($sql);
        foreach($list as $i=>$goods){
            $list[$i] = $this->goodsHandler($goods, $myLevel);
        }
        
        return $list;
    }
    
    /**
     * 获取商品的sku
     * @param unknown $goodsId
     */
    public function getSKU($goodsId, $buyer){
        if(!is_numeric($goodsId)){
            $this->error = '商品ID不能为空';
            return null;
        }
    
        $goods = $this->getById($goodsId);
        if(empty($goods) || $goods['is_del']){
            $this->error = '商品不存在';
            return null;
        }
        
        // 如果是套系商品，每隔5分钟更新一次信息
        if(!empty($goods['tao_id'])){
            //$tao = $this->query("SELECT last_sync FROM alibaba_goods WHERE tao_id=".$goods['tao_id']);
            //if(!empty($tao) && NOW_TIME - strtotime($tao[0]['last_sync']) >= 300){
            $alibabaModel = new AlibabaModel();
            $syncResult = $alibabaModel->syncGoods($goods['tao_id'], $goods['id']);
            if(!empty($syncResult['error'])){
                $goods['is_display'] = 0;
            }
            //}
        }

        $goods = $this->goodsHandler($goods, $buyer['agent_level']);

        // 获取产品信息
        $max_price = 0;
        $min_price = 0;
        foreach($goods['products'] as $index=>$product){
            $product = $this->goodsHandler($product, $buyer['agent_level']);
            $myPrice = $product['agents'][$buyer['agent_level']]['price'];
            
            if($myPrice > $max_price)
                $max_price = $myPrice;

            if($min_price == 0 || $myPrice < $min_price){
                $min_price = $myPrice;
            }

            $goods['products'][$index] = $product;
        }
        $goods['price'] = $min_price == $max_price ? $min_price : $min_price . '-'. $max_price;

        unset($goods['images']);
        unset($goods['pv']);
        unset($goods['uv']);
        return $goods;
    }
    
    /**
     * 获取商品详情
     * @return NULL|Ambigous <number, mixed, multitype:unknown number , unknown>
     */
    public function getDetail($goodsId, $buyer){
        if(!is_numeric($goodsId)){
            $this->error = '商品ID不能为空';
            return null;
        }
        
        $goods = $this
                 ->alias("goods")
                 ->field("goods.id, goods.sold_time, goods.buy_quota, goods.cat_id, goods.pay_type,
                     goods.title, goods.agent2_price, goods.agent3_price, goods.agent4_price, goods.price,
                     goods.original_price, goods.score, goods.stock, goods.hide_stock, goods.outer_id,
                     goods.pic_url, goods.images, goods.digest, goods.day_quota, goods.every_quota,
                     goods.agent_quota, goods.is_virtual, goods.freight_tid, goods.freight_type,
                     goods.member_discount, goods.points, goods.is_display, goods.sold_num, goods.order_num,
                     goods.invoice, goods.warranty, goods.`returns`, goods.created, goods.sku_json,
                     goods.template_id, goods.is_del, goods.weight, goods.shop_id, goods.tao_id, goods.parameters,
                     shop.name AS shop_name, goods.send_place, goods.remote_area")
                 ->join("shop ON shop.id=goods.shop_id")
                 ->where("goods.id=".$goodsId)
                 ->find();
        
        if(empty($goods) || $goods['is_del']){
            $this->error = '商品不存在';
            return null;
        }
        
        $goods = $this->formatter($goods);
        $goods = $this->goodsHandler($goods, $buyer['agent_level']);
        
        // 获取产品信息
        $max_price = 0;
        $min_price = 0;
        foreach($goods['products'] as $index=>$product){
            // 是否允许游客购买
            $product['visitors_quota'] = $goods['visitors_quota'];
            $product = $this->goodsHandler($product, $buyer['agent_level']);
            $myPrice = $product['agents'][$buyer['agent_level']]['price'];
        
            if($myPrice > $max_price)
                $max_price = $myPrice;
        
            if($min_price == 0 || $myPrice < $min_price){
                $min_price = $myPrice;
            }
        
            $goods['products'][$index] = $product;
        }
        
        return $goods;
    }
    
    /**
     * 获取产品
     */
    public function getProduct($shopId){
        $data = array('total' => 0, 'rows' => array());
        
        $where = "goods.is_del=0";
        if(!empty($_GET['title']))
            $where .= "AND goods.title LIKE '%".addslashes($_GET['title'])."%'";
        
        $data['total'] = $this->alias("goods")
                ->join("mall_product AS product ON product.goods_id=goods.id", "INNER")
                ->where($where)
                ->count();
        if($data['total'] == 0)
            return $data;
        

        $offset = I('get.offset/d', 0);
        $limit = I('get.limit/d', 50);
        
        $list = $this->alias("goods")
                ->field("product.id, product.sku_json, goods.post_fee, product.stock, goods.title")
                ->join("mall_product AS product ON product.goods_id=goods.id", "INNER")
                ->where($where)
                ->order("goods.id DESC")
                ->limit($offset, $limit)
                ->select();
        
        foreach($list as $i=>$item){
            $list[$i]['spec'] = $this->getSpec($item['sku_json']);
            unset($list[$i]['sku_json']);
        }
        
        $data['rows'] = $list;
        return $data;
    }
    
    /**
     * 获取产品信息
     */
    public function getProductList($_where){
        $data = array('total' => 0, 'rows' => array());
        $where = array();
        $offset = I('get.offset/d', 0);
        $limit = I('get.limit/d', 50);

        $where[] = "goods.is_del=0";
        if($_where['action'] == 'index'){
            $where[] = "goods.is_display=1 AND goods.stock>0";
        }else if($_where['action'] == 'soldout'){
            $where[] = "product.stock<=0";
        }else if($_where['action'] == 'no_display'){
            $where[] = "goods.is_display=0";
        }else if($_where['action'] == 'visitors'){
            $where[] = "goods.visitors_quota=1";
        }
        
        if(is_numeric($_where['shop_id'])){
            $where[] = "goods.shop_id=".$_where['shop_id'];
        }
        
        if(!empty($_where['title'])){
            $title = addslashes($_where['title']);
            $where[] = "(goods.title LIKE '%{$title}%' OR goods.outer_id like '%{$title}%')";
        }
        
        $innerJoin = " INNER JOIN mall_goods_sort AS goods_sort ON goods_sort.goods_id=goods.id";
        if(is_numeric($_where['tag'])){
            $innerJoin .= " INNER JOIN mall_goods_tag AS tag ON tag.goods_id=goods.id AND tag.tag_id=".$_where['tag'];
        }
        
        if($_where['action'] == 'soldout'){
            $innerJoin .= " INNER JOIN mall_product AS product ON product.goods_id=goods.id";
        }
        
        $where = count($where) > 0 ? " WHERE ".implode(" AND ", $where) : "";
        
        // 计算总数
        $_total = $this->query("SELECT COUNT(distinct goods.id) FROM mall_goods AS goods".$innerJoin.$where);
        $data['total'] = current($_total[0]);
        if($data['total'] == 0){
            return $data;
        }
        
        $groupBy = $_where['action'] == 'soldout' ? " GROUP BY goods.id" : "";
        
        $orderBy = "";
        switch ($_where['sort']){
            case 'title':
                $orderBy = "goods.title";
                break;
            case 'stock':
                $orderBy = "goods.stock";
                break;
            case 'sold_num':
                $orderBy = "goods.sold_num";
                break;
            case 'created':
                $orderBy = "goods.created";
                break;
            case 'sort':
                $orderBy = "goods_sort.sort";
                break;
        
        }
        
        if(empty($orderBy)){
            $orderBy = " ORDER BY goods_sort.sort DESC, goods_sort.display_time DESC, goods_sort.uv DESC";
        }else{
            $orderBy = " ORDER BY ".$orderBy." ".$_where['order'];
        }
        
        $sql = "SELECT goods.id, goods.title, goods.price, goods.pic_url, goods.stock, sort, goods.pay_type, goods.tao_id,
                       goods.sold_num, goods.pv, goods.uv, goods.created, goods.agent2_price, goods.agent3_price, goods.shop_id,goods.cost,
                       goods_sort.yesterday,goods_sort.sevenday
                FROM mall_goods AS goods
                {$innerJoin}
                {$where}
                {$groupBy}
                {$orderBy}
                LIMIT {$offset}, {$limit}";

        $data['rows'] = $this->query($sql);
        if($_where['action'] == 'soldout'){
            foreach ($data['rows'] as $i=>$item){
                $data['rows'][$i]['spec'] = get_spec_name($item['sku_json']);
                unset($data['rows'][$i]['sku_json']);
            }
        }
        
        return $data;
    }
    
    
    /**
     * 导出产品信息
     */
    public function export($_where){
        set_time_limit(0);
        
        $where = array();
        if($_where['action'] == 'index'){
            $where[] = "goods.is_display=1 AND goods.stock>0";
        }else if($_where['action'] == 'soldout'){
            $where[] = "product.stock<=0";
        }else if($_where['action'] == 'no_display'){
            $where[] = "goods.is_display=0";
        }else if($_where['action'] == 'visitors'){
            $where[] = "goods.visitors_quota=1";
        }
        
        if(is_numeric($_where['shop_id'])){
            $where[] = "goods.shop_id=".$_where['shop_id'];
        }
        
        if(!empty($_where['title'])){
            $title = addslashes($_where['title']);
            $where[] = "(goods.title LIKE '%{$title}%' OR goods.outer_id like '%{$title}%')";
        }

        $innerJoin  = " INNER JOIN mall_goods_sort AS goods_sort ON goods_sort.goods_id=goods.id";
        $innerJoin .= " INNER JOIN mall_product AS product ON product.goods_id=goods.id";
        if(is_numeric($_where['tag'])){
            $innerJoin .= " INNER JOIN mall_goods_tag AS tag ON tag.goods_id=goods.id AND tag.tag_id=".$_where['tag'];
        }
        
        $where = count($where) > 0 ? " WHERE ".implode(" AND ", $where) : "";
        
        $orderBy = "";
        switch ($_where['sort']){
            case 'title':
                $orderBy = "goods.title";
                break;
            case 'stock':
                $orderBy = "goods.stock";
                break;
            case 'sold_num':
                $orderBy = "goods.sold_num";
                break;
            case 'created':
                $orderBy = "goods.created";
                break;
            case 'sort':
                $orderBy = "goods_sort.sort";
                break;
                
        }
        
        if(empty($orderBy)){
            $orderBy = " ORDER BY goods_sort.sort DESC, goods_sort.display_time DESC, goods_sort.uv DESC";
        }else{
            $orderBy = " ORDER BY ".$orderBy." ".$_where['order'];
        }
        
        $sql = "SELECT goods.id, goods.title, goods.pv,goods.uv,goods.stock AS goods_stock, goods.sold_num AS goods_sold_num, goods.created AS goods_created, goods_sort.sort,goods_sort.yesterday,goods_sort.threeday,
                       goods_sort.sevenday,goods_sort.thiryday,product.id AS product_id,product.sku_json, product.price, product.agent2_price, product.agent3_price, product.outer_id, product.stock, product.sold_num,
                       product.created,product.cost
                FROM mall_goods AS goods
                {$innerJoin}
                {$where}
                {$orderBy}";
        $list = $this->query($sql);
        $date = date('Y-m-d H:i:s');
        // 加载PHPExcel
        vendor('PHPExcel.PHPExcel');
        $objPHPExcel = new \PHPExcel();
        
        // 设置文档基本属性
        $objPHPExcel->getProperties()
                    ->setCreator("微通联盟")
                    ->setLastModifiedBy("微通联盟")
                    ->setTitle($date)
                    ->setSubject($date)
                    ->setDescription(json_encode($_POST));
        
        // 读取第一个工作表
        $worksheet = $objPHPExcel->setActiveSheetIndex(0);
        $worksheet->setTitle('产品信息');
        
        $i=1;
        $worksheet
        ->setCellValue('A'.$i, '名称')
        ->setCellValue('B'.$i, '货号')
        ->setCellValue('C'.$i, '规格/型号')
        ->setCellValue('D'.$i, '员工价')
        ->setCellValue('E'.$i, '会员价')
        ->setCellValue('F'.$i, '零售价')
        ->setCellValue('G'.$i, '成本')
        ->setCellValue('H'.$i, '产品销量')
        ->setCellValue('I'.$i, '产品库存')
        ->setCellValue('J'.$i, '上架时间')
        ->setCellValue('K'.$i, '商品销量')
        ->setCellValue('L'.$i, '商品库存')
        ->setCellValue('M'.$i, '排序')
        ->setCellValue('N'.$i, 'PV')
        ->setCellValue('O'.$i, 'UV')
        ->setCellValue('P'.$i, '昨日销量')
        ->setCellValue('Q'.$i, '三日销量')
        ->setCellValue('R'.$i, '七日销量')
        ->setCellValue('S'.$i, '月销量');

        $goods = $product = $specProduct = array();
        
        foreach($list as $k=>$v){
            if(!isset($product[$v['id']])){
                $product[$v['id']] = 1;
            }else{
                $product[$v['id']] += 1;
            }
        }
        
        foreach($list AS $item){
            $i++;
            $spec = '';
            if(!isset($productSpec[$item['product_id']])){
                $spec = get_spec_name($item['sku_json']);
                $productSpec[$item['product_id']] = $spec;
            }else{
                $spec =  $productSpec[$item['product_id']];
            }
            
            if(!isset($goods[$item['id']])){
                $worksheet
                ->setCellValue('A'.$i, $item['title'])
                ->setCellValue('B'.$i, $item['outer_id'])
                ->setCellValue('C'.$i, $spec)
                ->setCellValueExplicit('D'.$i, $item['agent2_price'], \PHPExcel_Cell_DataType::TYPE_STRING)
                ->setCellValueExplicit('E'.$i, $item['agent3_price'], \PHPExcel_Cell_DataType::TYPE_STRING)
                ->setCellValueExplicit('F'.$i, $item['price'], \PHPExcel_Cell_DataType::TYPE_STRING)
                ->setCellValueExplicit('G'.$i, $item['cost'], \PHPExcel_Cell_DataType::TYPE_STRING)
                ->setCellValue('H'.$i, $item['sold_num'])
                ->setCellValue('I'.$i, $item['stock'])
                ->setCellValue('J'.$i, $item['goods_created'])
                ->setCellValue('K'.$i, $item['goods_sold_num'])
                ->setCellValue('L'.$i, $item['goods_stock'])
                ->setCellValue('M'.$i, $item['sort'])
                ->setCellValue('N'.$i, $item['pv'])
                ->setCellValue('O'.$i, $item['uv'])
                ->setCellValue('P'.$i, $item['yesterday'])
                ->setCellValue('Q'.$i, $item['threeday'])
                ->setCellValue('R'.$i, $item['sevenday'])
                ->setCellValue('S'.$i, $item['thiryday']);
                
                
                $worksheet->getStyle('A'.$i)->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
                $worksheet->getStyle('B'.$i)->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
                $worksheet->getStyle('C'.$i)->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
                $worksheet->getStyle('D'.$i)->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
                $worksheet->getStyle('E'.$i)->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
                $worksheet->getStyle('F'.$i)->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
                $worksheet->getStyle('G'.$i)->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
                $worksheet->getStyle('H'.$i)->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
                $worksheet->getStyle('I'.$i)->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
                $worksheet->getStyle('J'.$i)->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
                $worksheet->getStyle('K'.$i)->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
                $worksheet->getStyle('L'.$i)->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
                $worksheet->getStyle('M'.$i)->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
                $worksheet->getStyle('N'.$i)->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
                $worksheet->getStyle('O'.$i)->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
                $worksheet->getStyle('P'.$i)->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
                $worksheet->getStyle('Q'.$i)->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
                $worksheet->getStyle('R'.$i)->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
                $worksheet->getStyle('S'.$i)->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
               
                
                $goods[$item['id']] = 1;
            }else{
                $goods[$item['id']]++;
                $worksheet
                ->setCellValue('B'.$i, $item['outer_id'])
                ->setCellValue('C'.$i, $spec)
                ->setCellValue('D'.$i, $item['agent2_price'])
                ->setCellValue('E'.$i, $item['agent3_price'])
                ->setCellValue('F'.$i, $item['price'])
                ->setCellValue('G'.$i, $item['cost'])
                ->setCellValue('H'.$i, $item['sold_num'])
                ->setCellValue('I'.$i, $item['stock']);
                
            }
            
            if($goods[$item['id']] == $product[$item['id']] && $goods[$item['id']] > 1){
                $worksheet
                ->mergeCells("A".($i-($goods[$item['id']]-1)).":A".$i)
                ->mergeCells("J".($i-($goods[$item['id']]-1)).":J".$i)
                ->mergeCells("K".($i-($goods[$item['id']]-1)).":K".$i)
                ->mergeCells("L".($i-($goods[$item['id']]-1)).":L".$i)
                ->mergeCells("M".($i-($goods[$item['id']]-1)).":M".$i)
                ->mergeCells("N".($i-($goods[$item['id']]-1)).":N".$i)
                ->mergeCells("O".($i-($goods[$item['id']]-1)).":O".$i)
                ->mergeCells("P".($i-($goods[$item['id']]-1)).":P".$i)
                ->mergeCells("Q".($i-($goods[$item['id']]-1)).":Q".$i)
                ->mergeCells("R".($i-($goods[$item['id']]-1)).":R".$i)
                ->mergeCells("S".($i-($goods[$item['id']]-1)).":S".$i);
                
            }
        }
        // Redirect output to a client’s web browser (Excel2007)
        $text = iconv('UTF-8', 'GB2312', '产品信息');
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename="'.$text.date('YmdHis').'.xlsx"');
        header('Cache-Control: max-age=0');
        // If you're serving to IE 9, then the following may be needed
        //header('Cache-Control: max-age=1');
        
        // If you're serving to IE over SSL, then the following may be needed
        header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
        header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); // always modified
        header ('Cache-Control: cache, must-revalidate'); // HTTP/1.1
        header ('Pragma: public'); // HTTP/1.0
        
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
        $objWriter->save('php://output');
        exit;
    }
}
?>